import {
  ALL_PATH
} from '../router/index.js';
import querystring from 'querystring';

export default (request) => {
  return new Promise(async (resolve) => {
    // 解析url
    const urlObj = new URL(request.url, `http://${request.headers.host}`);
    const method = request.method.toLocaleLowerCase();

    // 生成唯一路由
    const apiKey = `${urlObj.pathname}&${method}`;

    // 当前路由path
    const routerPath = ALL_PATH.find(v => `/${v}` == apiKey);

    let params = {};
    
    // get,delete请求参数利用url对象的searchParams.forEach获取
    if (['get', 'delete'].includes(method)) {
      // 处理请求参数
      urlObj.searchParams.forEach((val, key, searchParams) => {
        params[`${key}`] = val;
      });
    }

    if (['put', 'post'].includes(method)) {
      let body = '';
      // 接收数据片段
      await request.on('data', chunk => {
        body += chunk.toString(); // 转换为字符串
      });
      params = querystring.parse(body); // 解析参数
    }

    resolve({
      params,
      routerPath
    })

  })
}
